import React, { Component } from 'react'
import store from './store'
// import { CHANGE_INPUT, ADD_LIST, DELETE_LIST } from './store/actionTypes'
import { changeInputValueAction, addListAction, deleteListAction } from './store/actionCreators'

class TodoList extends Component {
  constructor(props) {
    super(props)
    this.state = store.getState()
    //redux订阅，修改redux值
    store.subscribe(this.storeChange)
  }
  //执行订阅storeChange修改redux值
  storeChange = () => {
    this.setState(store.getState())
  }
  /**1、修改input输入框 */
  changeInputValue = (e) => {
    /**
      console.log(e.target.value)
      //建立action
      const action = {
        type: CHANGE_INPUT,
        value: e.target.value
      }
    */
    //dispatch派发action行为
    store.dispatch(changeInputValueAction(e.target.value))
  }
  /**2、点击新增按钮 */
  addList = () => {
    //dispatch派发action行为
    store.dispatch(addListAction())
  }
  /**3、点击删除按钮 */
  deleteList = (index) => {
    //dispatch派发action行为
    store.dispatch(deleteListAction(index))
  }
  render () {
    return (
      <div>
        <input
          type="text"
          placeholder='请输入待办事项'
          onChange={(e) => this.changeInputValue(e)}
          value={this.state.inputValue} />
        <button onClick={() => this.addList()}>添加</button>
        <hr />
        <ul>
          {
            this.state.listData.map((item, index) => {
              return (
                <li key={index}>
                  {item}
                  <button onClick={() => this.deleteList(index)}>x</button>
                </li>
              )
            })
          }
        </ul>
      </div>
    )
  }
}

export default TodoList